﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using Shell32;
using System.Windows.Forms;
namespace ConvertToGif
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            //拖拽事件绑定
            this.AllowDrop = true;
            this.DragEnter += (s, e) =>
            {
                if (e.Data.GetDataPresent(System.Windows.DataFormats.FileDrop))
                {
                    e.Effects = System.Windows.DragDropEffects.Link;
                }
                else
                {
                    e.Effects = System.Windows.DragDropEffects.None;
                    ShowMsg("拖入的不是文件");
                }
            };
            this.Drop += (s, e) =>
            {
                Array files = e.Data.GetData(System.Windows.DataFormats.FileDrop) as Array;
                string fileName = files.GetValue(0).ToString();
                ShowFileInfo(fileName);
            };

            progressOne.Visibility = Visibility.Hidden;
        }

        //选择文件
        private void btnSelect_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog _dialog = new OpenFileDialog();
            _dialog.Title = "选择视频文件";
            _dialog.Filter = "所有文件|*.*|视频文件|*.avi|视频文件|*.mp4|视频文件|*.flv|视频文件|*.mkv|视频文件|*.rmvb";
            _dialog.FileName = string.Empty;
            _dialog.RestoreDirectory = true;

            DialogResult result = _dialog.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.Cancel)
                return;
            ShowFileInfo(_dialog.FileName);
        }
        //开始转换
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string source = txtFullName.Text;
                string target = txtTargetName.Text;
                //验证
                if (string.IsNullOrEmpty(source))
                {
                    ShowMsg("要转换的视频文件不能为空");
                    return;
                }
                if (string.IsNullOrEmpty(target))
                {
                    ShowMsg("要保存的gif文件路径不存在");
                    return;
                }

                GifConverData data = new GifConverData()
                {
                    SourceFile = source,
                    TargetFile = target,
                    VideoSize = comboBox.SelectedValue.ToString().Replace("默认", ""),
                    Vframes = comboBox1.SelectedValue.ToString() == "默认" ? 0 : Convert.ToInt32(comboBox1.SelectedValue.ToString())
                };
                Action<object> actionNew = (q) =>
                {
                    GifConvert _convert = new GifConvert((GifConverData)q);
                    //响应事件
                    _convert.OnResponse = (text) =>
                    {
                        Action<string> action1 = (txt) =>
                        {
                            txtResponse.AppendText(txt);
                            txtResponse.AppendText("\r\n");
                            txtResponse.ScrollToEnd();
                        };
                        txtResponse.Dispatcher.BeginInvoke(action1, text);
                    };
                    //结束事件
                    _convert.OnEnd = (text) =>
                    {
                        Action actionHide = () =>
                        {
                            progressOne.Visibility = Visibility.Hidden;
                        };
                        progressOne.Dispatcher.BeginInvoke(actionHide);
                        ShowMsg("转换成功，处理时长：" + text);
                    };
                    _convert.Start();
                };
                //启动线程处理,如果因为异常完成，抛出异常内容
                Task convertTask = Task.Factory.StartNew(actionNew, data);
                convertTask.ContinueWith(t =>
                {
                    if (t.IsFaulted && t.Exception != null)
                    {
                        string msg = t.Exception.InnerException == null ? t.Exception.Message :t.Exception.InnerException.Message;
                        ShowMsg(msg);
                    }
                });
                progressOne.Visibility = Visibility.Visible;
            }
            catch (Exception ex)
            {
                ShowMsg(ex.Message, true);
            }
        }
        /// <summary>
        /// 显示视频文件信息
        /// </summary>
        /// <param name="filename"></param>
        private void ShowFileInfo(string filename)
        {
            FileInfo source = new FileInfo(filename);
            if (source.Exists == false)
                throw new Exception($"获取视频文件失败，{filename}");
            //文件名
            txtFullName.Text = filename;
            //输出文件名
            txtTargetName.Text = source.DirectoryName + "\\" + source.Name.Substring(0, source.Name.IndexOf(".")) + "_converted.gif";
            //获取文件信息
            #region 获取文件信息
            //初始化Shell接口
            ShellClass sh = new ShellClass();
            Folder dir = sh.NameSpace(System.IO.Path.GetDirectoryName(filename));
            FolderItem item = dir.ParseName(System.IO.Path.GetFileName(filename));
            //存放属性名和属性值
            Dictionary<string, string> dic = new Dictionary<string, string>();
            int[] indexList = new int[] {
                                0,1,
                306,308,307,305,
                27,28,
                2,3,4,
               //  303,304,
            };
            foreach (var i in indexList)
            {
                string key = dir.GetDetailsOf(null, i);
                string value = dir.GetDetailsOf(item, i);
                dic.Add(key, value);
            }
            listBox.ItemsSource = dic;
            #endregion
        }
        /// <summary>
        /// 弹框显示信息
        /// </summary>
        /// <param name="str"></param>
        private void ShowMsg(string str, bool IsError = false)
        {
            if (IsError)
                System.Windows.MessageBox.Show(str, "错误信息", MessageBoxButton.OK, MessageBoxImage.Error);
            else
                System.Windows.MessageBox.Show(str, "提示信息", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        #region 导航菜单
        //浏览微工具集网站
        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.gongjuji.net/?from=converttogif");
        }
        //关于对话框
        private void MenuItem_Click_1(object sender, RoutedEventArgs e)
        {
            About about = new About();
            about.ShowDialog();
        }
        #endregion
    }
}
